import React, { useReducer } from 'react';
import { Button, Input, Divider } from 'antd';
// 还可以用immer来改写, 更加的简洁
import dataReducer from "./reducer.js";


/*
  * 使用reducer带来的变化:
    1. 代码量变低
    2. 调试比较简单
    3. 代码的可读性, 可维护性比较高
    4. 前端自动化测试方便 Jest
    5. 组件的复用性降低
    6. 组件复用性比较强，建议用useState; 组件复用性比较弱，建议用useReducer;
*/
function ReducerComponent() {
  let [ data, dispatch ] = useReducer(dataReducer, {
    inputVal: '',
    list: []
  });

  const handleTextChange = (val) => {
    const action = {
      type: 'changeInput',
      value: val
    };
    dispatch(action);
  };
  const handleTextDataAdd = () => {
    const action = {
      type: 'changeAdd',
      value: data.inputVal
    };
    dispatch(action);
  };

  // 列表数据删除
  const handleTextDataDel = (index) => {
    const action = {
      type: 'changeDelete',
      value: index
    };
    dispatch(action);
  };

  return (
    <>
      <Divider />
      <h1>Reducer</h1>
      <div style={{display: "flex"}}>
        <Input
          style={{marginRight: "20px"}}
          value={data.inputVal}
          onChange={(e) => handleTextChange(e.target.value)}
          onKeyDown={(eve) => { eve.keyCode == 13 ? handleTextDataAdd() : null; }}
        />
        <Button onClick={handleTextDataAdd}>添加</Button>
      </div>
      <ul>
        {
          data.list.map((item, index) =>
            <li
              key={item.id}
              onClick={() => handleTextDataDel(index)}
            >
              { item.value }
            </li>
          )
        }
      </ul>
    </>
  )
}

export default ReducerComponent;